<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function monthly_report_add_page($id) {
    return drupal_get_form('monthly_report_edit_form',$id);
}

function monthly_report_edit_page($id) {
    return drupal_get_form('monthly_report_edit_form', $id);
}

function monthly_report_edit_form($form, &$form_state) {
    if (!empty($_GET['distributor_id'])) {
        $form_state['distributor_id'] = $_GET['distributor_id'];
    }
    if(empty( $form_state['distributor_id'])) {}else{
        $form['#distributor_id'] = $form_state['distributor_id'];
        $res = get_info($form['#distributor_id'],'distributor');
        $form['#distributor_name'] = $res[0]->distributor_name;
//        $addr_red = get_all_addrname($res[0]->addr_id);
//        $province = $addr_red[0]->province?$addr_red[0]->province:"";
//        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
//        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
//        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
//        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
//        $form['#farmer_addr'] =$province.$city.$county.$town.$village;
    }
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('monthly_report', 'monthly_report_id', $id);
        if (empty($record)) {
            drupal_set_message(t('月清月结相应信息不存在！'), 'status', FALSE);
            return $form;
        }
    }
    // 判断用户角色
    if(!nonghua_user_access('monthly_report', 'view', $id, !empty($record) ? $record->author_uid:0, !empty($record) ? $record->distributor_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    global $user;
    if (empty($record)) {
        _insert_date_selection_form($form,$form_state,5,date('Y'),date('n'),true,true);
    } else {
        _insert_date_selection_form($form,$form_state,5,$record->year, $record->month,true,true);
    }

    $uid = $user->uid;
    $user_info = _get_user_info($uid);
//    $init_distributor = isset( $record->distributor_id) && !empty($record->distributor_id) ? $record->distributor_id:'';
//    $distributor_options = array(
//        '' => '--经销商--',
//    );
//    if (isset($user_info['manager']) && $user_info['manager'] === '0') {//经理
//        $query = db_select('employee', 'e1');
//        $query->join('employee', 'e2', 'e2.manager_uid = e1.employee_id');
//        $query->condition('e1.department_id', 1, '=');
//        $query->condition('e2.department_id', 1, '=');
//        $query->condition('e1.employee_id', $uid, '=');
//        $query->join('salesman_distributor_map', 'sd', 'sd.salesman_id=e2.employee_id or sd.salesman_id ='.$uid);
//        $query->join('distributor', 'd', 'd.distributor_id = sd.distributor_id');
//        $query->leftJoin('distributor', 'D2', 'D2.parent_distributor_id = d.distributor_id');
//        $query->leftJoin('distributor', 'D3', 'D3.parent_distributor_id = D2.distributor_id');
//        $query->leftJoin('distributor', 'D4', 'D4.parent_distributor_id = D3.distributor_id');
//        $query->leftJoin('distributor', 'D5', 'D5.parent_distributor_id = D4.distributor_id');
//        $query->leftJoin('distributor', 'D6', 'D6.parent_distributor_id = D5.distributor_id');
//        $query->condition('d.level',1, '=');
//        $query->addField('d', 'distributor_id ','distributor_id');
//        $query->addField('d', 'distributor_name','distributor_name');
//
//        $query->addField('D2', 'distributor_id ','one_distributor_id');
//        $query->addField('D2', 'distributor_name','one_distributor_name');
//
//        $query->addField('D3', 'distributor_id','two_distributor_id');
//        $query->addField('D3', 'distributor_name','two_distributor_name');
//
//        $query->addField('D4', 'distributor_id','three_distributor_id');
//        $query->addField('D4', 'distributor_name','three_distributor_name');
//
//        $query->addField('D5', 'distributor_id','four_distributor_id');
//        $query->addField('D5', 'distributor_name','four_distributor_name');
//
//        $query->addField('D6', 'distributor_id','five_distributor_id');
//        $query->addField('D6', 'distributor_name','five_distributor_name');
//        $result_records = $query->execute();
//    } else {//业务员
//        $query = db_select('employee', 'e1');
//        $query->condition('e1.department_id', 1, '=');
//        $query->condition('e1.employee_id', $uid, '=');
//        $query->join('salesman_distributor_map', 'sd', 'sd.salesman_id=e1.employee_id or sd.salesman_id ='.$uid);
//        $query->join('distributor', 'd', 'd.distributor_id = sd.distributor_id');
//        $query->leftJoin('distributor', 'D2', 'D2.parent_distributor_id = d.distributor_id');
//        $query->leftJoin('distributor', 'D3', 'D3.parent_distributor_id = D2.distributor_id');
//        $query->leftJoin('distributor', 'D4', 'D4.parent_distributor_id = D3.distributor_id');
//        $query->leftJoin('distributor', 'D5', 'D5.parent_distributor_id = D4.distributor_id');
//        $query->leftJoin('distributor', 'D6', 'D6.parent_distributor_id = D5.distributor_id');
//        $query->condition('d.level',1, '=');
//        $query->addField('d', 'distributor_id ','distributor_id');
//        $query->addField('d', 'distributor_name','distributor_name');
//
//        $query->addField('D2', 'distributor_id ','one_distributor_id');
//        $query->addField('D2', 'distributor_name','one_distributor_name');
//
//        $query->addField('D3', 'distributor_id','two_distributor_id');
//        $query->addField('D3', 'distributor_name','two_distributor_name');
//
//        $query->addField('D4', 'distributor_id','three_distributor_id');
//        $query->addField('D4', 'distributor_name','three_distributor_name');
//
//        $query->addField('D5', 'distributor_id','four_distributor_id');
//        $query->addField('D5', 'distributor_name','four_distributor_name');
//
//        $query->addField('D6', 'distributor_id','five_distributor_id');
//        $query->addField('D6', 'distributor_name','five_distributor_name');
//        $result_records = $query->execute();
//    }
//
//    foreach($result_records as $key => $value){
//        if(!empty($value->five_distributor_id)){
//            $distributor_options[$value->distributor_id]      ="┅　".$value->distributor_name;
//            $distributor_options[$value->one_distributor_id]      ="　┅　".$value->one_distributor_name;
//            $distributor_options[$value->two_distributor_id]      ="　　┅　".$value->two_distributor_name;
//            $distributor_options[$value->three_distributor_id]    ="　　　┅　".$value->three_distributor_name;
//            $distributor_options[$value->four_distributor_id]     ="　　　　┅　".$value->four_distributor_name;
//            $distributor_options[$value->five_distributor_id]     ="　　　　　┅　".$value->five_distributor_name;
//        }else if(!empty($value->four_distributor_id)){
//            $distributor_options[$value->distributor_id]      ="┅　".$value->distributor_name;
//            $distributor_options[$value->one_distributor_id]      ="　┅　".$value->one_distributor_name;
//            $distributor_options[$value->two_distributor_id]      ="　　┅　".$value->two_distributor_name;
//            $distributor_options[$value->three_distributor_id]    ="　　　┅　".$value->three_distributor_name;
//            $distributor_options[$value->four_distributor_id]     ="　　　　┅　".$value->four_distributor_name;
//        }else if(!empty($value->three_distributor_id)){
//            $distributor_options[$value->distributor_id]      ="┅　".$value->distributor_name;
//            $distributor_options[$value->one_distributor_id]      ="　┅　".$value->one_distributor_name;
//            $distributor_options[$value->two_distributor_id]      ="　　┅　".$value->two_distributor_name;
//            $distributor_options[$value->three_distributor_id]    ="　　　┅　".$value->three_distributor_name;
//        }else if(!empty($value->two_distributor_id)){
//            $distributor_options[$value->distributor_id]      ="┅　".$value->distributor_name;
//            $distributor_options[$value->one_distributor_id]      ="　┅　".$value->one_distributor_name;
//            $distributor_options[$value->two_distributor_id]      ="　　┅　".$value->two_distributor_name;
//        }else if(!empty($value->one_distributor_id)){
//            $distributor_options[$value->distributor_id]      ="┅　".$value->distributor_name;
//            $distributor_options[$value->one_distributor_id]      ="　┅　".$value->one_distributor_name;
//        }else{
//            $distributor_options[$value->distributor_id]      ="┅　".$value->distributor_name;
//        }
//    }
//
//    if (isset($form_state['values']['distributor'])) {
//        if (!isset($distributor_options[$form_state['values']['distributor']])) {
//            $form_state['values']['distributor'] = '';
//        }
//    }
////    $form['distributor'] = _insert_login_salesman_distributor_selection_form($form,$form_state,$uid,$init_distributor);
//    $form['distributor'] = array(
//        '#prefix' => '<div id="distributor-wrapper-div">',
//        '#suffix' => '</div>',
//        '#type' => 'select',
//        '#title' => '选择经销商',
//        '#validated' => TRUE,
//        '#required' => TRUE,
//        '#options' => $distributor_options,
//        '#default_value' => $init_distributor,
//
//    );
    if(!empty($_GET['distributor_id'])){
        $record->distributor_id = $_GET['distributor_id'];
    }
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    if(isset($record)&&!empty($record)){
        $form_state['values']['distributor_id'] = $record->distributor_id;
        $form_state['values']['year'] = $record->year;
        $form_state['values']['month'] = $record->month;
    }

    if(isset($form_state['values']['distributor_id'])&&!empty($form_state['values']['distributor_id']) && !empty($form_state['values']['year'] )&& !empty($form_state['values']['month'])){
        $sql_sum = 'select SUM(this_month_instock) as this_month_instock, sum(this_month_stock) as this_month_stock,sum(this_month_sales)as this_month_sales from stock_info
             where distributor_id ='.$form_state['values']['distributor_id'].' and year = '.$form_state['values']['year'].' and month='.$form_state['values']['month'];
        $results = db_query($sql_sum);
        foreach($results as $result) {
            $this_month_instock = $result->this_month_instock;
            $this_month_sales = $result->this_month_sales;
            $this_month_stock = $result->this_month_stock;
        }
        $sql_sum_last_year = 'select SUM(this_month_instock) as this_month_instock, sum(this_month_stock) as this_month_stock,sum(this_month_sales)as this_month_sales from stock_info
             where distributor_id ='.$form_state['values']['distributor_id'].' and year = '.($form_state['values']['year']-1).' and month='.$form_state['values']['month'];
        $results = db_query($sql_sum_last_year);
        foreach($results as $result) {
            $last_year_this_month_instock = $result->this_month_instock;
            $last_year_this_month_sales = $result->this_month_sales;
            $last_year_this_month_stock = $result->this_month_stock;
        }
        $distributor_info = _get_user_info($form_state['values']['distributor_id']);
        if(@$distributor_info['inorout'] === '关内'){
            $sql_accumulative = 'select sum(this_month_sales)as this_month_sales from stock_info
             where distributor_id ='.$form_state['values']['distributor_id'].' and year = '.$form_state['values']['year'].' and month>=1 and month<='.$form_state['values']['month'];
            $results = db_query($sql_accumulative);
            foreach($results as $result) {
                $accumulative_total_sales = $result->this_month_sales;
            }
            $last_year_sql_accumulative = 'select sum(this_month_sales)as this_month_sales from stock_info
             where distributor_id ='.$form_state['values']['distributor_id'].' and year = '.($form_state['values']['year']-1).' and month>=1 and month<='.$form_state['values']['month'];
            $results = db_query($last_year_sql_accumulative);
            foreach($results as $result) {
                $last_year_accumulative_total_sales = $result->this_month_sales;
            }
        }else if(@$distributor_info['inorout'] === '关外'){
            if($form_state['values']['month']<9) {
                $date_max = $form_state['values']['year'] . '-0' . $form_state['values']['month'] . '-00';
                $date_min = ($form_state['values']['year'] - 1) . '-09' . '-00';
                $last_year_date_max = ($form_state['values']['year']-1).'-0'.$form_state['values']['month'].'-00';
                $last_year_date_min = ($form_state['values']['year']-2).'-09'.'-00';
            }else{
                if($form_state['values']['month']<10){
                    $date_max = $form_state['values']['year'] . '-0' . $form_state['values']['month'] . '-00';
                    $last_year_date_max = ($form_state['values']['year']-1).'-0'.$form_state['values']['month'].'-00';
                }else{
                    $date_max = $form_state['values']['year'] . '-' . $form_state['values']['month'] . '-00';
                    $last_year_date_max = ($form_state['values']['year']-1).'-'.$form_state['values']['month'].'-00';
                }
                $date_min = ($form_state['values']['year']) . '-09' . '-00';
                $last_year_date_min = ($form_state['values']['year']-1).'-09'.'-00';
            }
            unset($results);
            unset($sql_accumulative);
            $sql_accumulative = 'select sum(t.this_month_sales) as this_month_sales from
                 (select date_format(concat(year,\'-\',month,\'-00\'),\'%Y-%m-%d\') as date,distributor_id,this_month_sales from stock_info)t where
                        t.date >=\''.$date_min.'\' and t.date<=\''.$date_max.'\' and t.distributor_id =\''.$form_state['values']['distributor_id'].'\'';
            $results = db_query($sql_accumulative);
            foreach($results as $result) {
                $accumulative_total_sales = $result->this_month_sales;
            }
            unset($results);
            unset($sql_accumulative);
            $sql_accumulative = 'select sum(t.this_month_sales) as this_month_sales from
                 (select date_format(concat(year,\'-\',month,\'-00\'),\'%Y-%m-%d\') as date,distributor_id,this_month_sales from stock_info)t where
                  t.date >=\''.$last_year_date_min.'\' and t.date<=\''.$last_year_date_max.'\' and t.distributor_id =\''.$form_state['values']['distributor_id'].'\'';
            $results = db_query($sql_accumulative);
            foreach($results as $result) {
                $last_year_accumulative_total_sales = $result->this_month_sales;
            }
        }

    }
    $form['this_year_markup']['#markup'] = '<div id="stock-info-this-year-div">';
    $form['this_month_instock'] = array(
        '#type' => 'textfield',
        '#title' => '本月入库（吨）',
        '#prefix' => '<div id="stock-info-this-month-instock-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($this_month_instock)&&!empty($this_month_instock)?$this_month_instock:'',
    );
    unset($this_month_instock);
    $form['this_month_sales'] = array(
        '#type' => 'textfield',
        '#title' => '本月销量（吨）',
        '#prefix' => '<div id="stock-info-this-month-sales-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($this_month_sales) && !empty($this_month_sales) ? $this_month_sales:'',
    );
    unset($this_month_sales);
    $form['this_month_stock'] = array(
        '#type' => 'textfield',
        '#title' => '本月库存（吨）',
        '#prefix' => '<div id="stock-info-this-month-stock-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($this_month_stock) && !empty($this_month_stock) ? $this_month_stock:'',
    );
    unset($this_month_stock);
    $form['accumulative_total_sales'] = array(
        '#type' => 'textfield',
        '#title' => '累计销售（吨)',
//        '#description' => '关内经销商从1月份开始统计，关外经销商是从9月份开始统计',
        '#prefix' => '<div id="stock-info-accumulative-total-sales-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($accumulative_total_sales) && !empty($accumulative_total_sales) ? $accumulative_total_sales:'',
    );
    unset($accumulative_total_sales);
    $form['this_year_markup_close']['#markup'] = '</div>';

    $form['last_year_markup']['#markup'] = '<div id="stock-info-last-year-div">';
    $form['last_year_this_month_instock'] = array(
        '#type' => 'textfield',
        '#title' => '去年同期入库（吨）',
        '#prefix' => '<div id="last_year_stock-info-this-month-instock-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($last_year_this_month_instock)&&!empty($last_year_this_month_instock)?$last_year_this_month_instock:'',
    );
    unset($last_year_this_month_instock);
    $form['last_year_this_month_sales'] = array(
        '#type' => 'textfield',
        '#title' => '去年同期销量（吨）',
        '#prefix' => '<div id="last_year_stock-info-this-month-sales-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($last_year_this_month_sales) && !empty($last_year_this_month_sales) ? $last_year_this_month_sales:'',
    );
    unset($last_year_this_month_sales);
    $form['last_year_this_month_stock'] = array(
        '#type' => 'textfield',
        '#title' => '去年同期库存（吨）',
        '#prefix' => '<div id="last_year_stock-info-this-month-stock-div">',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($last_year_this_month_stock) && !empty($last_year_this_month_stock) ? $last_year_this_month_stock:'',
    );
    unset($last_year_this_month_stock);
    $form['last_year_accumulative_total_sales'] = array(
        '#type' => 'textfield',
        '#title' => '去年同期累计销售（吨）',
        '#prefix' => '<div id="last_year_stock-info-accumulative-total-sales-div">',
//        '#description' => '关内经销商从1月份开始统计，关外经销商是从9月份开始统计',
        '#suffix' => '</div>',
        '#disabled' => true,
        '#value' => isset($last_year_accumulative_total_sales) && !empty($last_year_accumulative_total_sales) ? $last_year_accumulative_total_sales:'',
    );
    unset($last_year_accumulative_total_sales);
    $form['last_year_markup_close']['#markup'] = '</div>';

    $form['this_month_received_payment'] = array(
        '#type' => 'textfield',
        '#title' => '当月回款',
        '#default_value' => !empty($record) ? $record->this_month_received_payment : '',
        '#required' => TRUE,
    );
    $form['accounts_receivable'] = array(
        '#type' => 'textfield',
        '#title' => '应收账款',
        '#default_value' => !empty($record) ? $record->accounts_receivable : '',
        '#required' => TRUE,
    );
    $form['payment_overdue'] = array(
        '#type' => 'textfield',
        '#title' => '逾期时间',
        '#default_value' => !empty($record) ? $record->payment_overdue : '',
        '#required' => TRUE,
    );

    $form['payment_credit'] = array(
        '#type' => 'textfield',
        '#title' => '信用占款',
        '#default_value' => !empty($record) ? $record->payment_credit : '',
        '#required' => TRUE,
    );
    $form['paulin_number'] = array(
        '#type' => 'textfield',
        '#title' => '篷布到期未返还数量',
        '#default_value' => !empty($record) ? $record->paulin_number : 0,
    );
    $form['paulin_overdue'] = array(
        '#type' => 'textfield',
        '#title' => '篷布逾期时间',
        '#default_value' => !empty($record) ? $record->paulin_overdue : '',
        '#size' => 32,
        '#maxlength' => 10,
    );
    $form['damage_info'] = array(
        '#type' => 'textarea',
        '#title' => '受损信息',
        '#default_value' => !empty($record) ? $record->damage_info : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['payment_info'] = array(
        '#type' => 'textarea',
        '#title' => '各经销商应收账款及到期篷布明细及管控措施',
        '#default_value' => !empty($record) ? $record->damage_info : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['promotion_info'] = array(
        '#type' => 'textarea',
        '#title' => '促销执行情况',
        '#default_value' => !empty($record) ? $record->promotion_info : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['unqualified_info'] = array(
        '#type' => 'textarea',
        '#title' => '不合格信息通报',
        '#default_value' => !empty($record) ? $record->unqualified_info : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['accident_info'] = array(
        '#type' => 'textarea',
        '#title' => '意外/事故信息',
        '#default_value' => !empty($record) ? $record->accident_info : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['pending_issues'] = array(
        '#type' => 'textarea',
        '#title' => '未解决事宜',
        '#default_value' => !empty($record) ? $record->pending_issues : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['competitor_info'] = array(
        '#type' => 'textarea',
        '#title' => '竞争者信息',
        '#default_value' => !empty($record) ? $record->competitor_info : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );
    $form['next_month_task'] = array(
        '#type' => 'textarea',
        '#title' => '下个月任务',
        '#default_value' => !empty($record) ? $record->next_month_task : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 200
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(2)!='add' ? '修改' : '添加',
        '#access' =>nonghua_user_access('monthly_report', 'edit', $id, !empty($record) ? $record->author_uid:0,!empty($record) ? $record->distributor_id:0) ,
    );
    return $form;
}
function stock_info_callback($form, &$form_state){
    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#stock-info-this-month-instock-div", render($form['this_month_instock'])),
            ajax_command_replace("#stock-info-this-month-sales-div", render($form['this_month_sales'])),
            ajax_command_replace("#stock-info-this-month-stock-div", render($form['this_month_stock'])),
            ajax_command_replace("#stock-info-accumulative-total-sales-div", render($form['accumulative_total_sales'])),
            ajax_command_replace("#last_year_stock-info-this-month-instock-div", render($form['last_year_this_month_instock'])),
            ajax_command_replace("#last_year_stock-info-this-month-sales-div", render($form['last_year_this_month_sales'])),
            ajax_command_replace("#last_year_stock-info-this-month-stock-div", render($form['last_year_this_month_stock'])),
            ajax_command_replace("#last_year_stock-info-accumulative-total-sales-div", render($form['last_year_accumulative_total_sales'])),
        )
    );
}
function monthly_report_edit_form_validate($form, &$form_state) {
    if(empty($form_state['values']['distributor_name'])){
        form_set_error('distributor_id', '必须填写 经销商');
    }
    if(!empty($form_state['values']['this_month_received_payment'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['this_month_received_payment']) || (strlen(explode('.',$form_state['values']['this_month_received_payment'])[0])>8)) {
            form_set_error('this_month_received_payment', "当月回款格式错误");
        }
    }
    if(!empty($form_state['values']['payment_overdue'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['payment_overdue']) || (strlen(explode('.',$form_state['values']['payment_overdue'])[0])>8)) {
            form_set_error('payment_overdue', "应收账款格式错误");
        }
    }
    if(!empty($form_state['values']['accounts_receivable'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['accounts_receivable']) || (strlen(explode('.',$form_state['values']['accounts_receivable'])[0])>8)) {
            form_set_error('accounts_receivable', "应收账款格式错误");
        }
    }
    if(!empty($form_state['values']['payment_credit'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['payment_credit']) || (strlen(explode('.',$form_state['values']['payment_credit'])[0])>8)) {
            form_set_error('payment_credit', "信用账款格式错误");
        }
    }
    if(!empty($form_state['values']['paulin_number'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['paulin_number']) || (strlen(explode('.',$form_state['values']['paulin_number'])[0])>8)) {
            form_set_error('paulin_number', "篷布到期未返还数量格式错误");
        }
    }
    if(!empty($form_state['values']['distributor_name'])){
        $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
        if(empty($distributor_id)){
            form_set_error('distributor_name', "经销商信息不存在！");
        }
    }
}

function monthly_report_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (arg(2) == 'add') { //add new monthly_report
        $nid = db_insert('monthly_report') // Table name no longer needs {}
        ->fields(array(
            'year' => $form_state['values']['year'],
            'month' => $form_state['values']['month'],
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'this_month_received_payment' => $form_state['values']['this_month_received_payment'],
            'accounts_receivable' => $form_state['values']['accounts_receivable'],
            'payment_overdue' => $form_state['values']['payment_overdue'],
            'payment_credit' => $form_state['values']['payment_credit'],
            'paulin_number' => $form_state['values']['paulin_number'],
            'paulin_overdue' => $form_state['values']['paulin_overdue'],
            'damage_info' => $form_state['values']['damage_info'],
            'payment_info' => $form_state['values']['payment_info'],
            'promotion_info' => $form_state['values']['promotion_info'],
            'unqualified_info' => $form_state['values']['unqualified_info'],
            'accident_info' => $form_state['values']['accident_info'],
            'pending_issues' => $form_state['values']['pending_issues'],
            'competitor_info' => $form_state['values']['competitor_info'],
            'next_month_task' => $form_state['values']['next_month_task'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
        if(!empty($_GET['distributor_id'])){
            drupal_goto('sales/monthly_report/list',array('query' => array('distributor_id' => $_GET['distributor_id'])));
        }
       drupal_goto('sales/monthly_report/add/'.$nid);
    } else {
        $nid = db_update('monthly_report') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'year' => $form_state['values']['year'],
            'month' => $form_state['values']['month'],
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'this_month_received_payment' => $form_state['values']['this_month_received_payment'],
            'accounts_receivable' => $form_state['values']['accounts_receivable'],
            'payment_overdue' => $form_state['values']['payment_overdue'],
            'payment_credit' => $form_state['values']['payment_credit'],
            'paulin_number' => $form_state['values']['paulin_number'],
            'paulin_overdue' => $form_state['values']['paulin_overdue'],
            'damage_info' => $form_state['values']['damage_info'],
            'payment_info' => $form_state['values']['payment_info'],
            'promotion_info' => $form_state['values']['promotion_info'],
            'unqualified_info' => $form_state['values']['unqualified_info'],
            'accident_info' => $form_state['values']['accident_info'],
            'pending_issues' => $form_state['values']['pending_issues'],
            'competitor_info' => $form_state['values']['competitor_info'],
            'next_month_task' => $form_state['values']['next_month_task'],
//            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('monthly_report_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['distributor_id'])){
            drupal_goto('sales/monthly_report/list',array('query' => array('distributor_id' => $_GET['distributor_id'])));
        }
//        drupal_goto('sales/monthly_report/list');
    }
}
